using GLib;
using Rob;
using DBus;

namespace Rob
{
	namespace Actions
	{
		public class SendSMS: Rob.Actions.Action
		{
			private string _text;
		 	private DBus.Connection conn;
		     	private dynamic DBus.Object sms;
		     	private dynamic DBus.Object dialer;
			private string sms_interface;
			private string sms_path;
			private string sms_name;
			private string dialer_interface;
			private string dialer_path;
			private string dialer_name;


			public string text
			{
				set{_text = value;}
				get{return _text;}
			}
			public bool load( KeyFile kf, string name)
			{
				try
				{
					base.load(kf,name);
					_text = kf.get_string(name, "text");
				}
				catch ( GLib.KeyFileError e)
				{
					GLib.critical("Could not load %s", name );
					return false;
				}
				return true;
			}
			public bool save(ref KeyFile kf)
			{
				try
				{
					base.save(ref kf);
					kf.set_string( this.name, "text", this._text );
				}
				catch( GLib.KeyFileError e)
				{
					GLib.critical("Could not save %s", name);
					return false;
				}
				return true;

			}
			construct 
			{
				_text = "";
				_type = "sendsms";
				sms_interface = "org.openmoko.PhoneKit";
				sms_path = "/org/openmoko/PhoneKit";
				sms_name  = "org.openmoko.PhoneKit.Sms"; 
				dialer_path = "/org/freesmartphone/Phone"; // "/org/openmoko/PhoneKit/Dialer"
				dialer_interface = "org.freesmartphone.Phone";
				dialer_name = "org.freesmartphone.Phone"; 	
			
			}
			public SendSMS()
			{
			}
			public void run()
			{
				try
				{
					this.conn =  DBus.Bus.get (DBus.BusType. SESSION);
					this.sms = conn.get_object(sms_name, sms_path, sms_interface);
					this.dialer = conn.get_object(dialer_name, dialer_path, dialer_interface);
					this.dialer.IncomingCall += incoming_call;
				}
				catch ( DBus.Error e)
				{
					GLib.critical("Could not get DBus Session Bus: %s", e.message);
				}


			}
			//private void incoming_call(dynamic DBus.Object dialer, int dummy1, string sender, string message_, int dummy2, uint dummy3)
			private void incoming_call(dynamic DBus.Object obj)//, string status, string peer, int line, string direction)
			{
				//stdout.printf("incomming call: %s %s\n",sender ,message_);
				//stdout.printf("%s calls status:%s\n", peer, status);
				string nr ;
				GLib.Error err;
				string uid;
				this.dialer.GetPeer(out nr);
				this.dialer.call("Release" , out err, typeof(string), "");
				//if( err != null)
				//	stderr.printf("Couln't hung up cal from %s\n", nr);
				this.sms.call( "Send", out err, typeof(string) , nr , typeof( string ), this.text, typeof( bool ), true, typeof( string ), out uid );

			}
			[ModuleInit]
			public Type register_rb_plugin (TypeModule module) 
			{
				stdout.printf ("Registering plugin %s\n", "SendSMS");
				return typeof (Rob.Actions.SendSMS);
			}
		}
	}
}
